#include <SDL.h>
#include <GL/glew.h>
#include "Device.h"


static SDL_Window* window;
static SDL_GLContext context;


bool CreateDevice(const char* title, size_t width, size_t height, size_t flags, size_t multisampleCount)
{
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
		return false;

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);

	if ((flags & kCreateDepthBuffer) == kCreateDepthBuffer)
	{
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
		SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	}
	else
	{
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
		SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
	}

    if (multisampleCount > 0)
    {
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multisampleCount);
    }

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
	if (NULL == window)
	{
		DestroyDevice();
		return false;
	}

	context = SDL_GL_CreateContext(window);

    glewExperimental = true;
	GLenum err = glewInit();
	if (err != GLEW_OK)
	{
		DestroyDevice();
		return false;
	}

	SDL_GL_SetSwapInterval(1);
    glGetError();

	return true;
}


void DestroyDevice()
{
	if (context)
		SDL_GL_DeleteContext(context);
	if (window)
		SDL_DestroyWindow(window);
}


void SwapBuffers()
{
	SDL_GL_SwapWindow(window);
}
